import { generateUUIDv4 } from '@/util/utils'
import { DownOutlined } from '@ant-design/icons'
import type { TreeDataNode } from 'antd'
import { Tree } from 'antd'
import { useEffect, useState } from 'react'
import '../index.less'

/* 插件 - tree 展示 */
const NestedTree = ({ data }: { data: any }) => {
  const renderItems = (data: any[]): TreeDataNode[] => {
    if (!Array.isArray(data)) return []

    return data
      .map(item => {
        if (typeof item === 'object' && item !== null) {
          const hasChildren = Array.isArray(item.children) && item.children.length > 0

          return {
            title: `${item.variable} [ ${item.type} ]`,
            key: item.variable + generateUUIDv4(),
            children: hasChildren ? renderItems(item.children) : undefined
          }
        }
        return null
      })
      .filter(Boolean)
  }

  return (
    <div className="workflow_tool_ant_tree_node">
      <Tree
        className="workflow_tool_ant_tree_node"
        showLine
        switcherIcon={<DownOutlined />}
        defaultExpandedKeys={['0-0']}
        treeData={renderItems(data)}
      />
    </div>
  )
}

export function ToolExportationCont({ info, editData }) {
  const [treeData, setTreeData] = useState([])

  useEffect(() => {
    if (info?.outputList) {
      setTreeData(info.outputList)
    }
  }, [info])

  return <NestedTree data={treeData} />
}
